package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //使用string缓存
    @Override
    public Result querryList() {
        //首先去redis中查关于分类的缓存
         String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY);
        //存在：返回
        if(StrUtil.isNotBlank(s))
        {
            List<ShopType> shopTypes = JSONUtil.toList(s, ShopType.class);
            return Result.ok(shopTypes);
        }
        // 不存在，去数据库中查
         List<ShopType> sort = query().orderByAsc("sort").list();
        //不存在，返回没有
        if(sort==null){
            return Result.fail("数据不存在");
        }

        //存在,存在redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY,JSONUtil.toJsonStr(sort));
        //返回



        //使用list缓存
         /*List<String> Redislist = stringRedisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY, 0, -1);
         //不为空
        if(Redislist!=null&&!Redislist.isEmpty()){
            List<ShopType> shopTypes=new ArrayList<>();
            for (String s1 : Redislist) {
                shopTypes.add(JSONUtil.toBean(s1,ShopType.class));

            }
            return Result.ok(shopTypes);
        }
        //空，去数据库查
        List<ShopType> sort1 = query().orderByAsc("sort").list();
        //为空
        if(sort1==null||sort1.isEmpty())
        {
            return Result.fail("数据不存在");
        }

        //不能为空，存到redis中
        for (ShopType shopType : sort1) {
            stringRedisTemplate.opsForList().rightPush(RedisConstants.CACHE_SHOP_TYPE_LIST_KEY, JSONUtil.toJsonStr(shopType));
        }

        return Result.ok(sort1);*/

        return Result.ok(sort);

    }




}
